package com.mjk.manager.magicapi.core.datasource.web;

import com.mjk.manager.magicapi.core.core.config.MagicConfiguration;
import com.mjk.manager.magicapi.core.core.model.JsonBean;
import com.mjk.manager.magicapi.core.core.web.MagicController;
import com.mjk.manager.magicapi.core.core.web.MagicExceptionHandler;
import com.mjk.manager.magicapi.core.datasource.model.DataSourceInfo;
import com.mjk.manager.magicapi.core.utils.JdbcUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import java.sql.Connection;

public class MagicDataSourceController extends MagicController implements MagicExceptionHandler {

    public MagicDataSourceController(MagicConfiguration configuration) {
        super(configuration);
    }

    @RequestMapping("/datasource/jdbc/test")
    @ResponseBody
    public JsonBean<String> test(@RequestBody DataSourceInfo properties) {
        try {
            Connection connection = JdbcUtils.getConnection(properties.getDriverClassName(), properties.getUrl(), properties.getUsername(), properties.getPassword());
            JdbcUtils.close(connection);
        } catch (Exception e) {
            return new JsonBean<>(e.getMessage());
        }
        return new JsonBean<>("ok");
    }
}
